import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Modal, Button, message, Table, Row, Col, Image } from 'antd';
import { MenuOutlined } from '@ant-design/icons';
import { arrayMoveImmutable } from 'array-move';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import styles from  './index.less';

const mapStateToProps = (state: any) => ({
  contentMng: state.contentMng,
  menu: state.menu,
  loading: state.loading.models['contentMng'],
});
const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);

class ContentSortModal extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    // console.log(props);
    this.state = {
      contentList: props.contentList.map((item: any, index: number) => {
        return {
          ...item,
          index,
          key: index + '',
        };
      }),
      tempId: sessionStorage.getItem('tempId'),
      isUniqImgConfig: JSON.parse(sessionStorage.getItem('isUniqImgConfig') || 'false'),
    };
  }

  onSortEnd = ({ oldIndex, newIndex }: any) => {
    const dataSource = this.state.contentList;
    // console.log(oldIndex, newIndex, dataSource);
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(dataSource.slice(), oldIndex, newIndex).filter(
        (el: any) => !!el,
      );
      // console.log('Sorted items: ', newData);
      // setDataSource(newData);
      // console.log(newData);
      this.setState({
        contentList: newData,
      });
    }
  };
  close = () => {
    const { closeModal } = this.props;
    closeModal();
  };
  confirmSort = () => {
    const {
      menu: { userProfile },
      dispatch,
    } = this.props;

    const list = this.state.contentList.map(
      (item: { sid: any; [key: string]: any }, index: any) => {
        return {
          sid: item.sid,
          orderIndex: index,
          templateSid: sessionStorage.getItem('tempId'),
          releaseState: item.releaseState,
          updateBy: userProfile.accountName,
        };
      },
    );
    dispatch({
      type: 'contentMng/sortTempContent',
      payload: {
        list,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.close();
          message.success('保存成功');
        }
      },
    });
    // closeModal();
  };
  render() {
    const { modalVisible, loading } = this.props;
    const { contentList } = this.state;
    // console.log(contentList);
    const dataSource = contentList;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.confirmSort} type="primary">
          确定
        </Button>
      </div>
    );
    const columns: Array<any> = [
      {
        title: '内容名称',
        dataIndex: 'contentName',
        className: 'drag_visible',
      },
      {
        title: '阅读/下载次数',
        dataIndex: 'applyCount',
        className: 'drag_visible',
      },
      {
        title: '',
        dataIndex: 'sort',
        width: 30,
        className: 'drag_visible',
        render: () => <DragHandle />,
      },
    ];
    const SortableItem = SortableElement((props: React.HTMLAttributes<HTMLTableRowElement>) => (
      <tr {...props} />
    ));
    const SortableBody = SortableContainer(
      (props: React.HTMLAttributes<HTMLTableSectionElement>) => <tbody {...props} />,
    );
    const DraggableContainer = (props: any) => (
      <SortableBody
        useDragHandle
        disableAutoscroll
        helperClass={styles["row_dragging"]}
        onSortEnd={this.onSortEnd}
        {...props}
      />
    );
    const DraggableBodyRow: React.FC<any> = ({ className, style, ...restProps }) => {
      // function findIndex base on Table rowKey props and should always be a right array index
      const index = dataSource.findIndex(x => x.index === restProps['data-row-key']);
      return <SortableItem index={index} {...restProps} />;
    };
    if (this.state.isUniqImgConfig) {
      const imgCol = {
        title: '缩略图',
        dataIndex: 'img',
        className: 'drag_visible',
        render: (text: any, record: any) => {
          const contentList = (record.contentJson && JSON.parse(record.contentJson)) || [];
          // const imgList = text?.split(',') || [];
          const imgList =
            contentList.find((item: { type: string }) => item.type == '3')?.content || [];
          if (imgList.length) {
            return imgList.length === 1 ? (
              <Image
                src={imgList[0].url}
                style={{ width: 75, height: 30, marginLeft: 5, marginTop: 5 }}
                fallback=""
              />
            ) : (
              <img
                src={imgList[0].url}
                style={{ width: 75, height: 30, marginLeft: 5, marginTop: 5, cursor: 'pointer' }}
                // onClick={() => {
                //   this.handleViewPic(imgList, record);
                // }}
              />
            );
          }
        },
      };
      columns.splice(0, 0, imgCol);
    }
    return (
      <Modal width={580} footer={footer} title="排序" visible={modalVisible} onCancel={this.close}>
        <Table
          pagination={false}
          dataSource={dataSource}
          columns={columns}
          rowKey="index"
          components={{
            body: {
              wrapper: DraggableContainer,
              row: DraggableBodyRow,
            },
          }}
        />
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(ContentSortModal);
